//
//  JKAddTagViewController.m
//  Baisi
//
//  Created by albert on 16/3/30.
//  Copyright (c) 2016年 albert. All rights reserved.
//

#import "JKAddTagViewController.h"
#import "JKTagButton.h"
#import "SVProgressHUD.h"
#import "JKTagTextField.h"

@interface JKAddTagViewController ()<UITextFieldDelegate>
/** contentView */
@property (nonatomic, weak) UIView *contentView;
/** 文本框 */
@property (nonatomic, weak) JKTagTextField *textField;
/** 添加标签按钮 */
@property (nonatomic, weak) UIButton *addButton;
/** 所有的标签按钮 */
@property (nonatomic, strong) NSMutableArray *tagButtons;
@end

@implementation JKAddTagViewController

#pragma mark - 懒加载
- (JKTagTextField *)textField{
    if (!_textField) {
        
        JKTagTextField *textField = [[JKTagTextField alloc] init];
        
        //监听删除按钮的点击
        __weak typeof(self) weakSelf = self;
        textField.deleteBlock = ^(){
            //如果有文字，直接返回
            if (weakSelf.textField.hasText) return;
            
            //删除最后一个标签
            [weakSelf tagButtonClick:[self.tagButtons lastObject]];
        };
        
        //监听文本框的输入可以直接添加target，注意事件是 UIControlEventEditingChanged
        //还可以使用通知 UITextFieldTextDidChangeNotification
        //不建议使用代理监听，因为对中文输入的监听不够好
        [textField addTarget:self action:@selector(textDidChange) forControlEvents:(UIControlEventEditingChanged)];
        
        //设置代理
        textField.delegate = self;
        
        [self.contentView addSubview:textField];
        _textField = textField;
    }
    return _textField;
}

- (UIView *)contentView{
    if (_contentView == nil) {
        
        UIView *contentView = [[UIView alloc] init];
        [self.view addSubview:contentView];
        _contentView = contentView;
    }
    return _contentView;
}

- (NSMutableArray *)tagButtons{
    if (_tagButtons == nil) {
        _tagButtons = [NSMutableArray array];
    }
    return _tagButtons;
}

//保证控件只创建一次，而且有时用有时不用的话，懒加载
//全世界的控件都可以搞成懒加载。。
- (UIButton *)addButton{
    if (_addButton == nil) {
        //创建按钮
        UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [button setBackgroundColor:JKTagBg];
        button.titleLabel.font = JKTagFont;
        
        //注意contentMode貌似仅适用于imageView
        //button.contentMode = UIViewContentModeBottomLeft;
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        button.contentEdgeInsets = UIEdgeInsetsMake(0, JKTagMargin, 0, JKTagMargin);
        
        //添加点击事件
        [button addTarget:self action:@selector(addButtonClick) forControlEvents:(UIControlEventTouchUpInside)];
        
        [self.contentView addSubview:button];
        _addButton = button;
    }
    return _addButton;
}

#pragma mark - 布局子控件
- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    
    //contentView
    self.contentView.x = JKTagMargin;
    self.contentView.y = JKNavBarHeight + JKTagMargin;
    self.contentView.width = self.view.width - 2 * self.contentView.x;
    self.contentView.height = JKScreenH;
    
    //textField
    self.textField.width = self.contentView.width;
    
    //添加标签按钮
    self.addButton.width = self.contentView.width;
    self.addButton.height = 35;
    
    //初始化标签。viewDidLayoutSubviews调用的比viewdidLoad略晚
    //因此初始化标签时，就调用添加标签方法，此时self。contentView.width == 0
    //viewDidLayoutSubviews可能会调用多次，因此需要判断一下
    if (self.tags.count) {
        [self setupTags];
        self.tags = nil;
    }
}

#pragma mark - 初始化
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    //进来时就弹出键盘
    [self.textField becomeFirstResponder];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //初始化导航控制器
    [self setupNav];
}

//初始化标签
- (void)setupTags{
    for (NSInteger i = 0; i < self.tags.count; i++) {
        self.textField.text = self.tags[i];
        [self addButtonClick];
    }
}

//初始化导航控制器
- (void)setupNav{
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.title = @"添加标签";
    
    //左侧按钮，使用自定义按钮，因为默认的高亮会有灰色
    JKItemButton *leftButton = [JKItemButton buttonWithType:(UIButtonTypeCustom)];
    leftButton.titleLabel.font = [UIFont systemFontOfSize:17];
    [leftButton setTitle:@"取消" forState:(UIControlStateNormal)];
//    leftButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    leftButton.contentEdgeInsets = UIEdgeInsetsMake(0, -8, 0, 0);
    [leftButton addTarget:self action:@selector(cancel) forControlEvents:(UIControlEventTouchUpInside)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    
    //右侧按钮，使用自定义按钮，因为默认的高亮会有灰色
    JKItemButton *rightButton = [JKItemButton buttonWithType:(UIButtonTypeCustom)];
    rightButton.titleLabel.font = leftButton.titleLabel.font;
    [rightButton setTitle:@"完成" forState:(UIControlStateNormal)];
    rightButton.size = CGSizeMake(50, 30);
//    rightButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    rightButton.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -8);
    [rightButton addTarget:self action:@selector(done) forControlEvents:(UIControlEventTouchUpInside)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
}

//取消
- (void)cancel{
    [self.view endEditing:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}

//完成
- (void)done{
    
    //NSMutableArray *tags = [NSMutableArray array];
    //for (JKTagButton *tagButton in self.tagButtons) {
    //    //获取按钮文字的两种方式
    //    //[tagButton titleForState:(UIControlStateNormal)];
    //    [tags addObject:tagButton.currentTitle];
    //}
    
    //kvc直接获取按钮的文字放在一个数组中
    NSArray *tags = [self.tagButtons valueForKeyPath:@"currentTitle"];
    //block有值就调用
    !self.tagsBlock ? : self.tagsBlock(tags);
    
    [self.view endEditing:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 监听文字改变
/**
 *  监听文本框文字改变
 *  该方法调用非常频繁，若在这里创建按钮的话，每调用一次就创建一次，耗费性能
 *  按钮只需要创建一次就，然后控制按钮是否隐藏就可以了
 *  因此按钮需要懒加载！！
 */
- (void)textDidChange{
    //这里只需要更新文本框的frame就行了
    [self updateTextFieldFrame];
    
    if (self.textField.hasText) {//有文字
        self.addButton.hidden = NO;self.addButton.hidden = !self.textField.hasText;
        self.addButton.y = CGRectGetMaxY(self.textField.frame) + JKTagMargin;
        [self.addButton setTitle:[NSString stringWithFormat:@"添加标签:%@", self.textField.text] forState:(UIControlStateNormal)];
        
        //获取最后一个字符
        NSString *text = self.textField.text;
        NSInteger length = text.length;
        //NSInteger maxLength = 5;
        NSString *lastLetter = [text substringFromIndex:length - 1];
        
        /*if (length > maxLength) {
            
            //获取前面的5个字符
            self.textField.text = [text substringToIndex:maxLength];
            //变成标签
            [self addButtonClick];
            
        }else */if (length > 1 && ([lastLetter isEqualToString:@"，"] || [lastLetter isEqualToString:@","])) {
            
            //如果最后一个字符是逗号，就变成标签
            //获取逗号前面的字符
            self.textField.text = [text substringToIndex:length - 1];
            //变成标签
            [self addButtonClick];
            
        }else if ([lastLetter isEqualToString:@"，"] || [text isEqualToString:@","]){
            
            //如果输入的第一个字符就是逗号，给个提示
            self.textField.text = nil;
            [self textDidChange];
            [JKProgressHUD showErrorWithStatus:@"标题不能为空"];
        }
        
    }else{//没文字
        self.addButton.hidden = YES;
    }
}

#pragma mark - 监听按钮点击

/**
 *  监听蓝色“添加按钮”点击
 */
- (void)addButtonClick{
    
    if (self.tagButtons.count >= 5) {
        [JKProgressHUD showErrorWithStatus:@"最多添加5个标签"];
        return;
    }
    
    //创建自定义的按钮
    JKTagButton *button = [JKTagButton buttonWithType:(UIButtonTypeCustom)];
    //设置文字和图片
    [button setTitle:self.textField.text forState:(UIControlStateNormal)];
    [button setImage:[UIImage imageNamed:@"chose_tag_close_icon"] forState:(UIControlStateNormal)];
    //要让高度和文本框保持一致
    //button.height = self.textField.height;
    
    //添加点击事件
    [button addTarget:self action:@selector(tagButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.contentView addSubview:button];
    //将按钮添加到数组
    [self.tagButtons addObject:button];
    
    //清空文本框的文字，并隐藏添加标签按钮
    self.textField.text = nil;
    self.addButton.hidden = YES;
    
    //更新frame
    [self updateTagButtonFrame];
    [self updateTextFieldFrame];
}

/**
 *  点击删除标签
 */
- (void)tagButtonClick:(JKTagButton *)tagButton{
    [tagButton removeFromSuperview];
    [self.tagButtons removeObject:tagButton];
    
    //动画更新frame
    [UIView animateWithDuration:0.25 animations:^{
        [self updateTagButtonFrame];
        [self updateTextFieldFrame];
    }];
}

#pragma mark - 处理子控件的frame
/**
 *  专门用来更新标签按钮frame
 */
- (void)updateTagButtonFrame{
    //更新标签按钮的frame
    for (NSInteger i = 0; i < self.tagButtons.count; i++) {
        JKTagButton *tagButton = self.tagButtons[i];
        if (i == 0) {//第一个标签按钮
            tagButton.x = 0;
            tagButton.y = 0;
            
        }else{//其它标签按钮
            //上一个标签按钮
            JKTagButton *lastTagButton = self.tagButtons[i - 1];
            
            //当前行剩余宽度
            CGFloat leftWidth = self.contentView.width - CGRectGetMaxX(lastTagButton.frame) - JKTagMargin;
            if (leftWidth >= tagButton.width) {//按钮显示在当前行
                tagButton.x = self.contentView.width - leftWidth;
                tagButton.y = lastTagButton.y;
                
            }else{//按钮显示在下一行
                //上一个标签按钮的最大Y值
                CGFloat lastTagButtonMaxY = CGRectGetMaxY(lastTagButton.frame);
                tagButton.x = 0;
                tagButton.y = lastTagButtonMaxY + JKTagMargin;
            }
        }
    }
}

/**
 *  更新textField的frame
 */
- (void)updateTextFieldFrame{
    //更新textField的frame
    JKTagButton *lastTagButton = self.tagButtons.lastObject;
    //剩余宽度
    CGFloat leftWidth = self.contentView.width - CGRectGetMaxX(lastTagButton.frame) - JKTagMargin;
    
    if (leftWidth >= [self textFieldTextWidth]) {
        self.textField.x = self.contentView.width - leftWidth;
        self.textField.y = lastTagButton.y;
    }else{
        self.textField.x = 0;
        self.textField.y = CGRectGetMaxY(lastTagButton.frame) + JKTagMargin;
    }
    
    //更新“添加标签按钮”的frame
    self.addButton.y = CGRectGetMaxY(self.textField.frame) + JKTagMargin;
}

/**
 *  textField的文字宽度
 */
- (CGFloat)textFieldTextWidth{
    CGFloat textW = [self.textField.text sizeWithAttributes:@{NSFontAttributeName : self.textField.font}].width;
    
    //当前行至少剩余100才让textField显示在当前行
    return MAX(100, textW);
}

#pragma mark - <UITextFieldDelegate>
//监听return key的点击
- (BOOL)textFieldShouldReturn:(JKTagTextField *)textField{
    if (self.textField.hasText) {//有文字
        [self addButtonClick];
    }else{//没文字
        [JKProgressHUD showErrorWithStatus:@"标题不能为空"];
    }
    return YES;
}

//该方法是指文本框的clearButton
//- (BOOL)textFieldShouldClear:(UITextField *)textField{
//    return YES;
//}
@end

#pragma mark - 自定义的按钮
@implementation JKItemButton

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
        [self setTitleColor:[UIColor redColor] forState:(UIControlStateHighlighted)];
        
        self.size = CGSizeMake(50, 30);
    }
    return self;
}
@end
